package com.jsh.action.basic;

import com.jsh.base.BaseAction;
import com.jsh.base.Log;
import com.jsh.model.po.Logdetails;
import com.jsh.model.po.Test2;
import com.jsh.model.po.Unit;
import com.jsh.model.vo.basic.Test2Model;
import com.jsh.service.basic.Test2IService;
import com.jsh.service.basic.UnitIService;
import com.jsh.service.basic.UserBusinessIService;
import com.jsh.util.PageUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.dao.DataAccessException;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by sam on 2017/11/28.
 */
public class Test2Action extends BaseAction<Test2Model>{
    private Test2IService testService;
    private UserBusinessIService userBusinessService;
    private Test2Model model = new Test2Model();
    private UnitIService unitService;

    public Test2Action() {
    }

    public void create() {
        Log.infoFileSync("==================开始调用增加测试信息方法create()===================");
        Boolean flag = Boolean.valueOf(false);

        try {
            Test2 test = new Test2();
            test.setName(this.model.getName());
            test.setEnabled(Boolean.valueOf(this.model.isEnabled()));
            if(this.model.getUnitId() != null) {
                test.setUnitId(new Unit(this.model.getUnitId()));
            } else {
                test.setUnitId((Unit)null);
            }

            test.setuName(this.model.getUName());
            this.testService.create(test);
            flag = Boolean.valueOf(true);
            tipMsg = " 成功";
            tipType = 0;
        } catch (DataAccessException e) {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>>>增加测试信息异常", e);
            flag = false;
            tipMsg = "失败";
            tipType = 1;
        } finally {
            try {
                toClient(flag.toString());
            } catch (IOException e) {
                Log.errorFileSync(">>>>>>>>>>>>增加测试信息回写客户端结果异常", e);
            }
        }

        logService.create(
                new Logdetails(getUser(), "增加测试", model.getClientIp(), new Timestamp(System.currentTimeMillis()),
                        tipType, "增加测试名称为  " + model.getName() + " " + tipMsg + "！", "增加测试" + tipMsg));
        Log.infoFileSync("==================结束调用增加测试方法create()===================");
    }

    /**
     * 删除测试
     *
     * @return
     */
    public String delete() {
        Log.infoFileSync("====================开始调用删除测试信息方法delete()================");
        try {
            testService.delete(model.getRoleID());
            tipMsg = " 成功";
            tipType = 0;
        } catch (DataAccessException e) {
            Log.errorFileSync(">>>>>>>>>>>删除ID为 " + model.getRoleID() + "  的测试异常", e);
            tipMsg = "失败";
            tipType = 1;
        }
        model.getShowModel().setMsgTip(tipMsg);
        logService.create(
                new Logdetails(getUser(), "删除测试", model.getClientIp(), new Timestamp(System.currentTimeMillis()),
                        tipType, "删除测试ID为  " + model.getRoleID() + " " + tipMsg + "！", "删除测试" + tipMsg));
        Log.infoFileSync("====================结束调用删除测试信息方法delete()================");
        return SUCCESS;
    }

    /**
     * 更新测试
     *
     * @return
     */
    public void update() {
        Boolean flag = false;
        try {
            Test2 test = (Test2)this.testService.get(this.model.getRoleID());
            System.out.println(test);
            test.setName(this.model.getName());
            test.setEnabled(Boolean.valueOf(this.model.isEnabled()));
            if(this.model.getUnitId() != null) {
                test.setUnitId(new Unit(this.model.getUnitId()));
            } else {
                test.setUnitId((Unit)null);
            }

            test.setuName(this.model.getUName());
            this.testService.update(test);
            flag = Boolean.valueOf(true);
            this.tipMsg = " 成功";
            this.tipType = 0;
        } catch (DataAccessException var11) {
            Log.errorFileSync(">>>>>>>>>>>>>修改测试ID为 ： " + this.model.getRoleID() + "信息失败", var11);
            flag = Boolean.valueOf(false);
            this.tipMsg = "失败";
            this.tipType = 1;
        } finally {
            try {
                this.toClient(flag.toString());
            } catch (IOException var10) {
                Log.errorFileSync(">>>>>>>>>>>>修改测试回写客户端结果异常", var10);
            }

        }

        this.logService.create(new Logdetails(this.getUser(), "更新测试", this.model.getClientIp(), new Timestamp(System.currentTimeMillis()), Short.valueOf(this.tipType), "更新测试ID为  " + this.model.getRoleID() + " " + this.tipMsg + "！", "更新测试" + this.tipMsg));
    }

    /**
     * 批量删除指定ID测试
     *
     * @return
     */
    public String batchDelete() {
        try {
            testService.batchDelete(model.getRoleIDs());
            model.getShowModel().setMsgTip("成功");
            // 记录操作日志使用
            tipMsg = " 成功";
            tipType = 0;
        } catch (DataAccessException e) {
            Log.errorFileSync(">>>>>>>>>>>批量删除测试ID为：" + model.getRoleID() + "信息异常", e);
            tipMsg = "失败";
            tipType = 1;
        }

        logService.create(
                new Logdetails(getUser(), "批量删除测试", model.getClientIp(), new Timestamp(System.currentTimeMillis()),
                        tipType, "批量删除测试ID为  " + model.getRoleID() + " " + tipMsg + "！", "批量删除测试" + tipMsg));
        return SUCCESS;
    }

    /**
     * 检查输入名称是否存在
     */
    public void checkIsNameExist() {
        Boolean flag = false;
        try {
            flag = testService.checkIsNameExist("name", model.getName(), "Id", model.getRoleID());
        } catch (DataAccessException e) {
            Log.errorFileSync(
                    ">>>>>>>>>>>>>>>>>检查测试名称为：" + model.getName() + " ID为：  " + model.getRoleID() + " 是否存在异常！");
        } finally {
            try {
                toClient(flag.toString());
            } catch (IOException e) {
                Log.errorFileSync(
                        ">>>>>>>>>>>>回写检查测试名称为：" + model.getName() + " ID为： " + model.getRoleID() + " 是否存在异常！", e);
            }
        }
    }

    /**
     * 查找测试信息
     *
     * @return
     */
    public void findBy() {
        try {
            PageUtil<Test2> pageUtil = new PageUtil();
            pageUtil.setPageSize(this.model.getPageSize());
            pageUtil.setCurPage(this.model.getPageNo());
            pageUtil.setAdvSearch(this.getCondition());
            this.testService.find(pageUtil);
            List<Test2> dataList = pageUtil.getPageList();

            //  开始拼接json数据
            // {"total":28,"rows":[
            // {"productid":"AV-CB-01","attr1":"Adult Male","itemid":"EST-18"}
            // ]}
            JSONObject outer = new JSONObject();
            outer.put("total", Integer.valueOf(pageUtil.getTotalCount()));
            JSONArray dataArray = new JSONArray();
            if(null != dataList) {
                Iterator var5 = dataList.iterator();

                while(var5.hasNext()) {
                    Test2 test = (Test2)var5.next();
                    JSONObject item = new JSONObject();
                    item.put("Id", test.getId());
                    item.put("Name", test.getName());
                    item.put("op", Integer.valueOf(1));
                    item.put("UnitId", test.getUnitId() == null?"":test.getUnitId().getId());
                    item.put("Enabled", test.getEnabled());
                    item.put("UName", test.getuName());
                    dataArray.add(item);
                }
            }

            outer.put("rows", dataArray);
            // 回写查询结果
            toClient(outer.toString());
        } catch (DataAccessException e) {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>>> 查找测试信息异常", e);
        } catch (IOException e) {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>>>回写查询测试信息结果异常", e);
        }
    }

    /**
     * 用户对应测试显示
     *
     * @return
     */
    public void findUsertest() {
        try {
            PageUtil<Test2> pageUtil = new PageUtil<Test2>();
            pageUtil.setPageSize(100);
            // pageUtil.setCurPage(model.getPageNo());

            pageUtil.setAdvSearch(getCondition_Usertest());
            testService.find(pageUtil);
            List<Test2> dataList = pageUtil.getPageList();

            // 开始拼接json数据
            JSONObject outer = new JSONObject();
            outer.put("id", 1);
            outer.put("text", "测试列表");
            outer.put("state", "open");
            // 存放数据json数组
            JSONArray dataArray = new JSONArray();
            if (null != dataList) {
                for (Test2 test : dataList) {
                    JSONObject item = new JSONObject();
                    item.put("id", test.getId());
                    item.put("text", test.getName());
                    // 勾选判断1
                    Boolean flag = false;
                    try {
                        flag = userBusinessService.checkIsUserBusinessExist("Type", model.getUBType(), "KeyId",
                                model.getUBKeyId(), "Value", "[" + test.toString() + "]");
                    } catch (DataAccessException e) {
                        Log.errorFileSync(">>>>>>>>>>>>>>>>> 设置用户对应的测试：类型" + model.getUBType() + " KeyId为： "
                                + model.getUBKeyId() + " 存在异常！");
                    }
                    if (flag == true) {
                        item.put("checked", true);
                    }
                    // 结束
                    dataArray.add(item);
                }
            }
            outer.put("children", dataArray);
            // 回写查询结果
            toClient("[" + outer.toString() + "]");
        } catch (DataAccessException e) {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>>>查找测试异常", e);
        } catch (IOException e) {
            Log.errorFileSync(">>>>>>>>>>>>>>>>>>>回写查询测试结果异常", e);
        }
    }

    /**
     * 拼接搜索条件
     *
     * @return
     */
    private Map<String, Object> getCondition() {
        /**
         * 拼接搜索条件
         */
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("Name_s_like", model.getName());
        condition.put("Id_s_order", "asc");
        return condition;
    }

    /**
     * 拼接搜索条件-用户对应测试
     *
     * @return
     */
    private Map<String, Object> getCondition_Usertest() {
        /**
         * 拼接搜索条件
         */
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("Id_s_order", "asc");
        return condition;
    }

    // =============以下spring注入以及Model驱动公共方法，与Action处理无关==================
    @Override
    public Test2Model getModel() {
        return model;
    }



    public void setTestService(Test2IService testService) {
        this.testService = testService;
    }

    public void setUserBusinessService(UserBusinessIService userBusinessService) {
        this.userBusinessService = userBusinessService;
    }
}
